import { put, takeEvery } from 'redux-saga/effects';
import { SIGINUP, SignupAction, signupSuccess, signupFail, SIGNIN, signinSuccess, signinFail, SigninAction } from '../actions/auth.actions';
import axios from 'axios';
import { API } from '../../config';

function* handleSignup(action: SignupAction) {
  try {
    yield axios.post(`${API}/signup`, action.payload);
    yield put(signupSuccess());
  } catch (error: any) {
    yield put(signupFail(error));
  }
}

function* handleSignin(action: SigninAction) {
  try {
    let response: object = yield axios.post(`${API}/signin`, action.payload);
    localStorage.setItem('jwt', JSON.stringify(response));
    yield put(signinSuccess());
  } catch (error: any) {
    yield put(signinFail(error));
  }
}

export default function* authSaga() {
  // 注册
  yield takeEvery(SIGINUP, handleSignup);
  // 登录
  yield takeEvery(SIGNIN, handleSignin);
}
